from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3 as sql

app = Flask(__name__)
app.secret_key = 'your_secret_key'

DATABASE = 'movies.db'
DATABASE2 = 'users.db'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 接收用户名和密码
        username = request.form['username']
        password = request.form['password']

        # 创建连接
        with sql.connect(DATABASE2) as con:
            cur = con.cursor()
            # 插入新用户
            cur.execute("select username,password from users where username = ? and password = ?", (username, password))
            user = cur.fetchall()
            if user:
                flash('登录成功。', 'success')
                return redirect(url_for('films'))
            con.commit()

            # 如果是GET请求，直接渲染登录页面
    return render_template('index.html')


# @app.route('/search/<filmName>')
def search(filmName):
    filmName = request.form.get('filmName')
    try:
        with sql.connect(DATABASE) as con:
            cur = con.cursor()
            cur.execute("select * FROM films WHERE filmName = ?", (filmName,))
            con.commit()
        flash(f'电影 ID {filmName} 查询成功', 'success')
        return redirect(url_for('searchfilm'))

    except sql.Error as e:
        flash(f'数据库错误: {e}', 'error')
    return redirect(url_for('films'))


@app.route('/films', methods=['GET', 'POST'])
def films():
    try:
        if request.method == 'POST':
            filmName = request.form.get("filmName")
            search_query = '%' + filmName + '%' if filmName else '%'
            with sql.connect(DATABASE) as conn:
                conn.row_factory = sql.Row
                cur = conn.cursor()
                cur.execute('SELECT filmId, filmName, filmScore, inq, playable FROM films WHERE filmName LIKE ?', (search_query,))
                films = cur.fetchall()
            return render_template('film.html', films=films)
        else:
            with sql.connect(DATABASE) as conn:
                conn.row_factory = sql.Row
                cur = conn.cursor()
                cur.execute('SELECT filmId, filmName, filmScore, inq, playable FROM films')
                films = cur.fetchall()
            return render_template('film.html', films=films)
    except sql.Error as e:
        # 处理数据库连接或查询错误
        return f"An error occurred: {e}", 500
    except Exception as e:
        # 处理其他可能的错误
        return f"An unexpected error occurred: {e}", 500

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        try:
            username = request.form['username']
            password = request.form['password']

            # 创建连接
            with sql.connect(DATABASE2) as con:
                cur = con.cursor()
                # 插入新用户
                cur.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
                con.commit()
                flash('注册成功，请登录。', 'success')
                return redirect(url_for('login'))
        except sql.Error as e:
            flash(f'数据库错误: {e}', 'error')
    return render_template('zhuce.html')


@app.route('/forget', methods=['GET', 'POST'])
def forget():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if not username or not password:
            flash('用户名和新密码不能为空。', 'error')
            return render_template('wangji.html')  # 确保模板文件名正确
        try:
            with sql.connect(DATABASE2) as con:
                cur = con.cursor()
                cur.execute("UPDATE users SET password = ? WHERE username = ?", (password, username))
                con.commit()
            flash('密码修改成功，请重新登录。', 'success')
            return redirect(url_for('login'))
        except sql.Error as e:
            flash(f'数据库错误: {e}', 'error')

    return render_template('wangji.html')


@app.route('/toEdit', methods=['GET', 'POST'])
def toEdit():
    if request.method == 'POST':
        filmId = request.form.get('filmId')
        filmName = request.form.get('filmName')
        filmScore = request.form.get('filmScore')
        inq = request.form.get('inq')
        playable = request.form.get('playable')

        if not filmName or not filmScore:
            flash('电影名和电影上映时间不能为空。', 'error')
            return render_template('filmEdit.html')

        try:
            with sql.connect(DATABASE) as con:
                cur = con.cursor()
                cur.execute("UPDATE films SET filmName = ?, filmScore = ?, inq = ?, playable = ? WHERE filmId = ?;",
                            (filmName, filmScore, inq, playable, filmId))
                con.commit()

            flash('修改成功。', 'success')
            return redirect(url_for('films'))

        except sql.Error as e:
            flash(f'数据库错误: {e}', 'error')

    return render_template('filmEdit.html')


@app.route('/delete/<int:filmId>', methods=['GET'])
def delete(filmId):
    try:
        with sql.connect(DATABASE) as con:
            cur = con.cursor()
            cur.execute("DELETE FROM films WHERE filmId = ?", (filmId,))
            con.commit()
        flash(f'电影 ID {filmId} 已删除', 'success')
        return redirect(url_for('films'))

    except sql.Error as e:
        flash(f'数据库错误: {e}', 'error')
    return redirect(url_for('films'))


if __name__ == '__main__':
    app.run(port=8080, debug=True)
